package controllers
{
	import flash.events.Event;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import org.dexter.sendDexterEvent;

	public class FileTransController
	{
		private var files:Vector.<FileReference> = new Vector.<FileReference>();
		public function FileTransController()
		{
		}
		[DexterEvent]
		public function browseFile(type:Array = null):void{
			var file:FileReference = new FileReference();
			file.addEventListener(Event.SELECT,onBrowseSelect);
			file.browse(type);
		}
		private function onBrowseSelect(event:Event):void{
			var file:FileReference = event.target as FileReference;
			files.push(file);
			file.addEventListener(Event.COMPLETE,onLoadComplete);
			file.load();
		}
		private function onLoadComplete(event:Event):void{
			var file:FileReference = event.target as FileReference;
			file.removeEventListener(Event.COMPLETE,onLoadComplete);
			sendDexterEvent("fileLoadComplete",file);
			files.splice(files.indexOf(file),1);
		}
		[DexterEvent]
		public function saveFile(data:ByteArray,defaultFileName:String = null):void{
			var file:FileReference = new FileReference();
			file.addEventListener(Event.CANCEL,onSaveCancel);
			file.addEventListener(Event.COMPLETE,onSaveComplete);
			file.save(data,defaultFileName);
			files.push(file);
		}
		private function onSaveCancel(event:Event):void{
			var file:FileReference = event.target as FileReference;
			file.removeEventListener(Event.CANCEL,onSaveCancel);
			files.splice(files.indexOf(file),1);
		}
		private function onSaveComplete(event:Event):void{
			var file:FileReference = event.target as FileReference;
			file.removeEventListener(Event.COMPLETE,onSaveComplete);
			files.splice(files.indexOf(file),1);
		}
	}
}